const https = require('https');
const { URL, TOKEN } = require('../config/shop');
const path = require('path');

// 缓存对象
const cache = {};

function request(options, data = null, url,isCache = true) {
  return new Promise((resolve, reject) => {
    console.log('请求', path.join(URL, url));
    options.headers['token'] = `${TOKEN}`;

    if (cache[url] && isCache) {
      resolve(cache[url]);
      return;
    }

    const req = https.request(path.join(URL, url), options, (res) => {
      let responseData = '';
      res.on('data', (chunk) => {
        responseData += chunk;
      });
      res.on('end', () => {
        try {
          const result = JSON.parse(responseData);
          if (isCache) {
            cache[url] = result;
          }
          if (result.code !== 0) {
            reject(result.msg);
          }
          resolve(result);
        } catch (error) {
          resolve(responseData); // 如果响应不是 JSON 格式
        }
      });
    });

    req.setTimeout(5000, () => {
      req.destroy();
      reject(new Error(`Request to ${url} timed out after 5000ms`));
    });

    req.on('error', (error) => {
      reject(new Error(`Request to ${url} failed: ${error.message}`));
    });

    if (data) {
      req.write(JSON.stringify(data));
    }
    req.end();
  });
}

module.exports = {
  get(url, params,isCache) {
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    };
    if (params) {
      url =
                url +
                '?' +
                Object.keys(params)
                  .map((key) => `${key}=${params[key]}`)
                  .join('&');
    }
    return request(options, null, url,isCache);
  },
  post(url, data,isCache) {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    };
    return request(options, data, url,isCache);
  },
};
